{% extends 'user/base.html' %}

{% block content %}
<div class="container mx-auto px-4 py-8 max-w-3xl">
        <div class="bg-white rounded-lg shadow-md p-6">
            <h1 class="text-2xl font-bold mb-6 text-gray-800">选择感兴趣的标签</h1>
            <p class="text-gray-600 mb-4">请选择 1-3 个你感兴趣的标签</p>

            <div class="grid grid-cols-2 md:grid-cols-5 gap-8 mb-8">
                {% for tag in tags %}
                    <div class="tag-item rounded-lg border border-gray-200 p-4 text-center">
                        {{ tag.name }}
                    </div>
                {% endfor %}
            </div>

            <div class="flex items-center justify-between border-t pt-4">
                <div class="text-gray-600">
                    已选择 <span id="selected-count">0</span>/3
                </div>
                <button id="submit-btn" class="!rounded-button bg-primary text-white px-8 py-2 disabled:opacity-50 disabled:cursor-not-allowed">
                    提交
                </button>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
    {{ super() }}
    <script>
        const tagItems = document.querySelectorAll('.tag-item');
        const submitBtn = document.getElementById('submit-btn');
        const selectedCountEl = document.getElementById('selected-count');
        let selectedCount = 0;

        tagItems.forEach(item => {
            item.addEventListener('click', () => {
                if (!item.classList.contains('selected') && selectedCount >= 3) {
                    return;
                }

                item.classList.toggle('selected');
                selectedCount = document.querySelectorAll('.tag-item.selected').length;
                selectedCountEl.textContent = selectedCount;

                submitBtn.disabled = selectedCount === 0 || selectedCount > 3;
            });
        });

        submitBtn.addEventListener('click', () => {
            const selectedTags = Array.from(document.querySelectorAll('.tag-item.selected'))
                                    .map(item => item.textContent.trim());
            console.log(selectedTags);
            fetchRequest('/user/tags',
                {
                    selectedTags: selectedTags
                },
                {
                    redirect: '{{ url_for('user.index') }}'
                });
        });
    </script>
{% endblock %}